
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
var app = getApp()


Page({

  /**
   * 页面的初始数据
   */
  data: {
    goods:[],
    reimages: [],

    images: [],
    col1: [],
    col2: [],


    onelogin: true,
    // 统计计数
    areanum: 0,
    // 优惠卷
    couponArr: [],
    topImages: 'http://m.qpic.cn/psc?/V14ZaBeY40XWC8/zkoezU7GGNbZGOF.DPhgQVgKh0Fw63ZhFQsd0hetQ8T6CBTPzbnz3dz1WfeDXiG6wY3NwfQcy1Y7Ry49HK1QdM9SKG1QzVXMBdXM0bH80fc!/b&bo=nQLyAJ0C8gADCSw!&rf=viewer_4',
    couponLeftImages: 'http://m.qpic.cn/psc?/V14ZaBeY40XWC8/zkoezU7GGNbZGOF.DPhgQXDCLspq1L1upRR.ZiRnZuFvq1XezxpUwmIc4ky9cr0DEpxn.YXOFA15Y03Wwkk2zJSBTVERFZsf3KTl5vSZorE!/b&bo=lgCWAJYAlgADCSw!&rf=viewer_4',
    closeBtnImages: 'http://m.qpic.cn/psc?/V14ZaBeY40XWC8/zkoezU7GGNbZGOF.DPhgQZjV2a5npNMM5D47K1jMLBHO3ccXXkEwsTHa*69Gi8pCGkdmz4imEISAR0fRbZj7*malDMMANN7ZzH8oI6XDWDk!/b&bo=QABAAEAAQAADCSw!&rf=viewer_4',
    // 是否显示优惠劵弹窗
    isShowCouponPopUp: false,
    // 测试
    // isShowCouponPopUp: true,
    //功能模块 
    functions: [
      {
        name: '满二减一',
        numbers: '',
        // iconpath: '../images/code.png',
        classifier: "Share",
        color: "orange",
        path: ""
      },
      {
        name: '五杯送一',
        numbers: "",
        color: "cyan",
        // iconpath: '../images/topic.png',
        classifier: "Topic",
        path: "",
      },
    ],
    // 轮播图 
    banner: [
      { 'gphoto': "/static/images/address.png" },
      { 'gphoto': "/static/images/close.gif" },
      { 'gphoto': "/static/images/about_us.png" }
    ],
  },


  box_right(e) {
    wx.navigateTo({
      url: '/pages/index/map/map',
    })
    console.log('e1:', '外卖')
  },
  box_left(e) {
    wx.navigateTo({
      url: '/pages/index/map/map',
    })
    console.log('e2:', '自取')
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {



    this.loginstatus()
    // var that = this
    // wx.getSetting({
    //   success(res) {

    //     // that.setData({
    //     //   isShowCouponPopUp:true
    //     // })
    //     if (res.authSetting['scope.userInfo'])  //此处判断是否登录
    //     {
    //       wx.setStorageSync('onelogin', 'false')
    //       console.log('getSetting:res:',res)
    //       let token=wx.getStorageSync('token')
    //       console.log(token)
    //       if(!token){
    //         wx.setStorageSync('onelogin', 'true')
    //         wx.navigateTo({
    //           url: '/pages/me/login/login',
    //         })
    //       }
    //     }
    //   }
    // })

    // 判断用户是不是第一次登陆
    // this.loginstatus() 
    this.setData({
      isShowCouponPopUp: false
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let one = 0;
    // 优惠卷劣币
    let that = this;
    this.setData({
      couponArr: []
    })
    console.log(this.data.couponArr)
    let onelogin = this.data.onelogin;
    console.log(onelogin)
    //  if(onelogin==true){
    util.request(api.CouponsList).then(res => {
      console.log('res', res)
      console.log('res', res.data.usercoupon.length)
      if (res.errno == 0) {
        let usercouponlist = []
        let coupon = res.data.usercoupon;
        console.log('coupon:', coupon)
        if (res.data.usercoupon.length > 0) {
          for (let i = 0; i < res.data.usercoupon.length; i++) {
            console.log('coupon[i]', coupon[i])
            let usercoupon = {}
            usercoupon['CouponName'] = coupon[i]['coupon_name']
            usercoupon['CouponTypeName'] = "满" + coupon[i]['minmoney'] + "元" + '立减' + coupon[i]['submoney'] + '元'
            usercoupon['CouponMoney'] = coupon[i]['submoney']
            usercoupon['HasItBeenClaimed'] = false
            usercoupon['id'] = coupon[i]['id']
            usercoupon['coupon_sn'] = coupon[i]['coupon_sn']
            usercoupon['use_end_data'] = coupon[0]['end_time']
            usercouponlist.push(usercoupon)
          }

          this.setData({
            couponArr: usercouponlist,
            areanum: usercouponlist.length,
            isShowCouponPopUp: true
          })
        }



        console.log('usercouponlist:', usercouponlist)
        wx.setStorageSync('usercouponlist', usercouponlist)
      }
    })
    //  this.setData({
    //   //  onelogin:false
    //  })

    //  }


    // this.setData({
    //   isShowCouponPopUp:false
    // })
    // 获取优惠卷列表
    // CouponName: 'weianl红包',
    // CouponTypeName: '满10000元可用',
    // CouponMoney: 1000,
    // HasItBeenClaimed: true,
    // if(one==0){
    //   one=1
    //   util.request(api.CommonUserCoupon).then(res=>{
    //     console.log(res)
    //     if(res.data.errno==0 ){
    //           console.log('res:',res)
    //           let  usercouponlist=[]
    //           let coupon=res.data.usercoupon;
    //           console.log('coupon:',coupon.length)
    //           for(let i=0;i<coupon.length;i++){
    //             let usercoupon={}
    //             console.log(coupon[i]['coupon_name'])
    //             usercoupon['CouponName']=coupon[i]['coupon_name']
    //             usercoupon['CouponTypeName']="满"+coupon[i]['min_goods_amount']+"元可用"
    //             usercoupon['CouponMoney']=coupon[i]['type_money']
    //             usercoupon['HasItBeenClaimed']=false
    //             usercoupon['id']=coupon[i]['id']
    //             usercoupon['coupon_sn']=coupon[i]['coupon_sn']
    //             usercoupon['use_end_data']=coupon[i]['use_end_data']
    //             usercouponlist.push(usercoupon)
    //           }

    //           let flag=that.data.onelogin;
    //           console.log(flag)
    //           if(flag==true){
    //             let coupons=wx.getStorageSync('usercouponlist');
    //             // let coupons=this.data.couponArr;
    //             console.log(coupons)
    //             for (let i = 0; i < coupons.length; i++) {
    //               console.log(coupons[i])
    //               usercouponlist.push(coupons[i])
    //             }
    //           }

    //           console.log(usercouponlist)
    //           this.setData({
    //             couponArr:usercouponlist,
    //             areanum:usercouponlist.length,
    //             isShowCouponPopUp:true
    //           })
    //           console.log('usercouponlist:',usercouponlist)
    //           wx.setStorageSync('usercouponlist', usercouponlist)
    //     }
    // });
    // }


    // 获取优惠卷列表
    // CouponName: 'weianl红包',
    // CouponTypeName: '满10000元可用',
    // CouponMoney: 1000,
    // HasItBeenClaimed: true,
    // util.request(api.NewUserCoupon).then(res=>{
    //   if(res.data.errno==0){
    //     console.log('res:',res)
    //     let  usercouponlist=[]
    //     let coupon=res.data.usercoupon[0];
    //     console.log('coupon:',coupon)
    //     let usercoupon={}
    //     usercoupon['CouponName']=coupon['coupon_name']
    //     usercoupon['CouponTypeName']="满"+coupon['min_goods_amount']+"元可用"
    //     usercoupon['CouponMoney']=coupon['type_money']
    //     usercoupon['HasItBeenClaimed']=false
    //     usercoupon['id']=coupon['id']
    //     usercoupon['coupon_sn']=coupon['coupon_sn']
    //     usercoupon['use_end_data']=coupon['use_end_data']
    //     usercouponlist.push(usercoupon)
    //     console.log('usercouponlist:',usercouponlist)
    //     wx.setStorageSync('usercouponlist', usercouponlist)
    //   }
    // })
    // let usercouponlist=wx.getStorageSync('usercouponlist');
    // console.log(usercouponlist)
    // this.setData({
    //   couponArr:usercouponlist
    // })



    // 获取轮播图
    // util.request(api.Banner).then(res=>{
    util.request(api.BannerList).then(res => {

      let banners = res.data.banners;
      console.log('banners:', banners)
      that.setData({
        banner: banners
      })
    })
    // 获取类型列表
    util.request(api.MenuList).then(res => {

      if (res.errno == 0) {
        console.log('res:', res)
        let menuslist = res.data.menuslist;
        let datagoodslist = res.data.datagoodsliat;
        // menuslist,datagoodslist)
        console.log('res:', menuslist.length)
        this.setData({
          menuslist,
          datagoodslist
        })
      }
    })
  // 自己的接口
    util.request(api.HotGoodsList).then(res => {
      console.log('res:', res)
      if (res.errno == 0) {
        let goods = res.data.goods;
        this.setData({
          goods:goods
        });


      }
    })

    // 
    // console.log(that.data.banners);

   




  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // console.log('res:',1)
    // this.setData({
    //   col1: [],
    //   col2: []
    // })
    // this.onLoad();
    // wx.stopPullDownRefresh();
  },



  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //打开优惠劵弹窗
  openTheCouponPopUp: function () {
    var that = this;
    setTimeout(() => {
      // 先开启优惠劵弹窗
      that.setData({
        isShowCouponPopUp: true
      })
      // 设置优惠劵弹窗打开动画
      var animation = wx.createAnimation({
        duration: 400,
        timingFunction: 'linear',
      })
      that.animation = animation;
      animation.scale(1).step();
      that.setData({
        animationData: animation.export()
      })
    }, 400)
  },
  //关闭优惠劵弹窗
  closeTheCouponPopUp() {
    // 设置优惠劵弹窗关闭动画
    var animation = wx.createAnimation({
      duration: 300,
      timingFunction: 'linear',
    })
    this.animation = animation;
    animation.scale(0).step();
    this.setData({
      animationData: animation.export(),
    })
    //执行完动画后再关闭
    setTimeout(() => {
      this.setData({
        isShowCouponPopUp: false
      })
    }, 200)
  },
  //领取单个优惠劵
  getCoupons: function (e) {
    console.log('e:', e)
    let that = this;
    let num = that.data.areanum;
    console.log(num)
    if (num <= 1) {
      this.closeTheCouponPopUp();
    }
    let id = e.currentTarget.dataset.id;
    let coupon_sn = e.currentTarget.dataset.coupon_sn;
    let index = e.currentTarget.dataset.index;
    let couponArr = this.data.couponArr;
    // 修改后台优惠卷数量
    // util.request(api.UpdateCoupon,{
    // console.log(res)
    //存储用户优惠卷
    util.request(api.AddUserCoupon, {
      coupon_sn: coupon_sn,
      openid: wx.getStorageSync('openid')
    }, "POST").then(res => {
      console.log(res)
      if (res.success) {
        // 领取之后健一
        num = num - 1;
        that.setData({
          areanum: num
        })
        util.request(api.SubCoupon, {
          id: id
        }, "POST").then(res => {
          console.log(res)
        })
        wx.showToast({
          title: '领取成功',
          icon: 'success'
        })
        couponArr[index].HasItBeenClaimed = true;
        that.setData({
          couponArr: couponArr
        })
      } else {
        wx.showToast({
          title: '你已经有此优惠卷',
          duration: 2000,
          icon: 'error'
        })
      }
    }).catch(err => {
    })
    // this.closeTheCouponPopUp()
  },
  //已领取优惠劵
  alreadyReceived: function () {
    wx.showToast({
      title: '已领取，可在卡包查看',
      icon: 'none'
    })
  },
  //领取全部优惠劵
  getAllCoupons: function () {
    let that = this;
    let num = that.data.areanum;
    var couponArr = this.data.couponArr;
    couponArr.forEach((item) => {
      item.HasItBeenClaimed = true;
    })
    this.setData({
      couponArr: couponArr
    })

    for (let i = 0; i < couponArr.length; i++) {
      util.request(api.SubCoupon, {
        id: couponArr[i]['id']
      }, "POST").then(res => {
        if (res.data.errno == 0) {
          // console.log(res)
          //存储用户优惠卷
          util.request(api.AddUserCoupon, {
            coupon_sn: couponArr[i]['coupon_sn'],
            openid: wx.getStorageSync('openid')
          }, "POST").then(res => {
            console.log(res)
            // 领取之后健一
            num = num - 1;
            that.setData({
              areanum: num
            })
          })
        }
      })
    }
    wx.showToast({
      title: '领取成功，已放入卡包',
      icon: 'none',
      complete: res => {
        that.closeTheCouponPopUp()
      }
    })


  },
  loginstatus() {
    var that = this
    wx.getSetting({
      success(res) {

        // that.setData({
        //   isShowCouponPopUp:true
        // })
        if (res.authSetting['scope.userInfo'])  //此处判断是否登录
        {
          that.setData({
            onelogin: false
          })
          console.log('getSetting:res:', res)
          let token = wx.getStorageSync('token')
          console.log(token)
          console.log(that.data.onelogin)
          if (!token) {
            that.setData({
              onelogin: true
            })
            wx.navigateTo({
              url: '/pages/me/login/login',
            })
          }
        }
      }
    })
  },
  // 优惠卷专区
  togetcoupons() {
    console.log('res:', 1111)
    wx.navigateTo({
      url: '/pages/index/coupons/coupons',
    })
  },
  // 加载图片

  //  ===============================================================

  // 购买
  togethoods(e) {
    // console.log(e.currentTarget.dataset.gid);
    let id = e.currentTarget.dataset.id;
    let datagoodslist = this.data.datagoodslist;
    let togoods = datagoodslist.map(item => {
      if (item.id == id) {
        let good = {}
        good['gid'] = item.id
        good['good_gname'] = item.gname
        good['good_photo'] = item.gphoto
        good['good_price'] = item.price
        good['number'] = 1
        good['openid'] = wx.getStorageSync('openid')
        return good;
      }
    })
    togoods = togoods.filter(item => item);
    console.log("goods:", togoods)
    wx.setStorageSync('subOrders', togoods)
    wx.navigateTo({
      url: '/pages/catalog/order/order',
    })

  },
  togetgood(e) {
    let id = e.currentTarget.dataset.id;
    let datagoodslist = this.data.goods;
    let togoods = datagoodslist.map(item => {
      if (item.id == id) {
        let good = {}
        good['gid'] = item.id
        good['good_gname'] = item.gname
        good['good_photo'] = item.gphoto
        good['good_price'] = item.price
        good['number'] = 1
        good['openid'] = wx.getStorageSync('openid')
        return good;
      }
    })
    togoods = togoods.filter(item => item);
    console.log("goods:", togoods)
    wx.setStorageSync('subOrders', togoods)
    wx.navigateTo({
      url: '/pages/catalog/order/order',
    })
  }

})